//
//  DeviceCellViewController.m
//  sentorise
//
//  Created by admin on 2025/8/28.
//

#import "DeviceCellViewController.h"
#import "GlobalDefine.h"
#import "BTManager.h"
#import "DeviceCellTableViewCell.h"

@interface DeviceCellViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (nonatomic, strong) NSMutableArray    *finalserialBalance;
@property (nonatomic, strong) NSMutableArray    *finalserialVoltageCount;
@property (nonatomic, strong) NSMutableArray    *finalserialVoltageValue;

@property (nonatomic, strong) NSTimer *queryTimer; //数据定时器
@property (nonatomic, assign) NSInteger queryCount;

@end

@implementation DeviceCellViewController
{
    int serialBalance[32];
    int serialVoltage[32];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topSpace.constant = IphoneX ? 54 : 20;
    self.finalserialBalance = [[NSMutableArray alloc] init];
    self.finalserialVoltageCount = [[NSMutableArray alloc] init];
    self.finalserialVoltageValue = [[NSMutableArray alloc] init];
    [self.finalserialVoltageCount addObjectsFromArray:@[@"1", @"2", @"3", @"4"]];
    [self.finalserialVoltageValue addObjectsFromArray:@[@"0.00", @"0.00", @"0.00", @"0.00"]];
    self.titleLabel.text = NSLocalizedString(@"Cell", nil);

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];

    [self.tableView registerNib:[UINib nibWithNibName:@"DeviceCellTableViewCell" bundle:nil] forCellReuseIdentifier:@"DeviceCellTableViewCell"];
    
    [self queryData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.queryTimer invalidate];
    self.queryTimer = nil;
}

- (void)queryData {
    WeakSelf
    self.queryTimer = [NSTimer scheduledTimerWithTimeInterval:2 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (weakSelf.queryCount % 2 == 0) {
            [weakSelf queryBMS];
        }else {
            [weakSelf queryBatteryTemperature];
        }
        weakSelf.queryCount ++;
    }];
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReciveData:(NSNotification *)notification {
    NSData *reciveData = notification.object;
    Byte *dataBytes = (Byte*)reciveData.bytes;
    if (dataBytes[2]==0x4c) {
        //3.1 主控读取电池电压数据
        for (int t=0;t<32;t++) {
            int voltage = dataBytes[3+t*2]*256 + dataBytes[3+t*2+1];
            serialVoltage[t] = voltage;
        }
    }
    if ((dataBytes[2]==0x32) & (reciveData.length>30)) {
        //放电电流
        NSInteger disChargingCurrent = dataBytes[3+0xd*2]*256+dataBytes[3+0xd*2+1];
        //充电电流
        NSInteger chargingCurrent = dataBytes[3+0xc*2]*256+dataBytes[3+0xc*2+1];
        NSInteger current = disChargingCurrent;
        if (chargingCurrent>0) current = chargingCurrent;
        
        //3.2 主控读取电池温度电流等信息
        //1-16 均衡状态
        int serialBalance16 = dataBytes[3+0x17*2]*256 + dataBytes[3+0x17*2+1];
        //17-32 均衡状态
        int serialBalance32 = dataBytes[3+0x18*2]*256 + dataBytes[3+0x18*2+1];
        int andbit = 1;
        int andValue = 1;
        for(int t = 0; t < 16; t++) {
            andValue = serialBalance16 & andbit;
            if (andValue > 0) {
                serialBalance[t] = 1;
            }else {
                serialBalance[t] = 0;
            }
            andbit = andbit<<1;
        }
        for(int t = 0; t < 16; t++) {
            andValue = serialBalance32 & andbit;
            if (andValue > 0) {
                serialBalance[t+16] = 1;
            }else {
                serialBalance[t+16] = 0;
            }
            andbit = andbit<<1;
        }
        [self.finalserialBalance removeAllObjects];
        [self.finalserialVoltageCount removeAllObjects];
        [self.finalserialVoltageValue removeAllObjects];
        for (int t = 0; t < 32; t++) {
            if (serialVoltage[t] < 61000) {
                [self.finalserialVoltageCount addObject:[NSString stringWithFormat:@"%i", t+1]];
                [self.finalserialBalance addObject:[NSString stringWithFormat:@"%i", serialBalance[t]]];
                [self.finalserialVoltageValue addObject:[NSString stringWithFormat:@"%i", serialVoltage[t]]];
            }
        }
        [self.tableView reloadData];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.finalserialVoltageCount.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceCellTableViewCell *cell = (DeviceCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DeviceCellTableViewCell"];
    cell.index = indexPath.section;
    cell.numV = [self.finalserialVoltageValue[indexPath.section] description];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 10)];
    view.backgroundColor = [UIColor clearColor];
    
    return view;
}

- (void)queryBMS {
    //主机读取电池电压数据
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD0;
    bytes[3] = 0x00;
    bytes[4] = 0x00;
    bytes[5] = 0x26;
    bytes[6] = 0xfc;
    bytes[7] = 0xd0;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryBatteryTemperature {
    //3.2 主控读取电池温度电流等信息
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD0;
    bytes[3] = 0x26;
    bytes[4] = 0x00;
    bytes[5] = 0x19;
    bytes[6] = 0x5d;
    bytes[7] = 0x0b;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}


@end
